import { wait } from "./wait";

const _: Record<symbol, [boolean, boolean]> = {};

/**
 * 超级节流，等待上一次异步调用结束后才能进行下一次调用
 * @param fn
 * @param interval
 * @param callback 回调状态
 */
export const throttle = <T>(fn: T, interval?: number, callback?: (arg: [boolean, boolean]) => void) => {
    const key = Symbol();
    _[key] = [false, false];
    return (async (...args: any) => {
        callback?.(_[key]);
        if (_[key][0] || _[key][1]) {
            return;
        }
        if (interval !== undefined) {
            _[key][1] = true;
            wait(interval).then(() => {
                _[key][1] = false;
            });
        }
        _[key][0] = true;
        const _fn = fn as (...args: any[]) => Promise<any>;
        return _fn(...args).then(value => {
            _[key][0] = false;
            return value;
        }).catch(reason => {
            _[key][0] = false;
            return Promise.reject(reason);
        });
    }) as T;
};